<?php
require_once ('DbUtils.php');
class Page {

    public $bean = null;
    public $filter = null;
    public $page_size = 15;
    public $page_count = null;
    public $cur_page = 0;
    public $connection = null;
    public $rows = null;
    public $orderBy = "";
    public $record_num = 0;
    public $cache_filter = false;
    public $submit_form_index = 0;

    /**
     * 分页查询某个模型的记录
     * @param $b            需要查询的模型实例（必填）
     * @param $f            过滤条件  （非必填）
     * @param $orderBy      排序字符串（非必填）
     * @param $loadChild    是否加载从表记录 （非必填）
     * @param $con          数据库连接对象 （非必填）
     * @param $pagesize     分页尺寸默认为20 （非必填）
     * @return 返回符合查询条件的模型列表
     */
    public static function FetchPageJson($b, $f= null,$orderBy="",$loadChild=false, $con = null, $pagesize = 20){
        $page = new Page($b, $f, $con , $pagesize );

        return $page->fetchJson($f,$orderBy,$loadChild);
    }

    public function Page($b, $f, $con = null, $pagesize = 20) {
        if($b instanceof AbstractBean){
            $this->bean = $b;    
        }
        else{
            $this->bean = AbstractBean::LoadBean($b);
        }
        
        $this->filter = $f;
        $this->page_size = $pagesize;
        if (!empty($_REQUEST["page_size"])) {
            $this->page_size = $_REQUEST["page_size"];
        }
        $this->connection = $con;
        $primarykey = $this->bean->getPrimaryKey() ;
        if ($primarykey != null && $primarykey != "") {
            $this->orderBy = "order by " . $primarykey  . " desc";
        }
    }

    
    public function fetchArray($ft = null,$groupBy="",$orderBy="") {
		
    	//$this->bean->connection = DbUtils::pdo_connection();

        if (!empty($_REQUEST["cur_page"])) {
            $this->cur_page = $_REQUEST["cur_page"];
        }
        if ($this->cur_page == 0) {
            $limit = $this->page_size;
        } else if ($this->cur_page > 0) {
            $limit = ($this->cur_page) * $this->page_size . "," . $this->page_size;
        }
        if ($ft != null) {
            $this->rows = $this->bean->fetchArray($ft, $this->orderBy, $limit,$groupBy);
            $this->record_num = $this->bean->getRecordCount($ft);
        } else {
            $this->rows = $this->bean->fetchArray($this->filter, $this->orderBy, $limit,$groupBy);
            $this->record_num = $this->bean->getRecordCount($this->filter);
        }
        $this->page_count = ceil($this->record_num / $this->page_size);
		
        return $this->rows;
    }




    public function fetchJson($ft = null,$orderBy="",$loadChild = false){
        //$beanList = $this->fetchBean($ft,$groupBy,$orderBy);
        $pageCtrl = array();
        $beanList = array();
        $page = array();

        if ($ft != null) {
            $this->record_num = $this->bean->getRecordCount($ft);
        } else {
            $this->record_num = $this->bean->getRecordCount($this->filter);
        }
        $this->page_count = ceil($this->record_num / $this->page_size);

        if (!empty($_REQUEST["page_no"])) { 
            $this->cur_page = $_REQUEST["page_no"];
        }

       
        if($this->cur_page>=$this->page_count){
            $this->cur_page = $this->page_count;
        }
        $start_index = 0;
        if (!empty($_REQUEST["limit"])) {

            $this->page_size  = $_REQUEST["limit"];
        }

        if (!empty($_REQUEST["start"])) {
            $start_index  = $_REQUEST["start"];
           
        }

        $realPageSize=$this->page_size;        
        if ($this->cur_page == 0 && $start_index ==0) {
            $limit = $realPageSize;
        } else if ($this->cur_page > 0) {
            if($this->record_num - ($this->cur_page-1) * $this->page_size < $realPageSize){
                $realPageSize = $this->record_num - ($this->cur_page-1) * $this->page_size;
            }
            $limit = ($this->cur_page-1) * $this->page_size . "," . $realPageSize;
        }
        else if($start_index>0){
            if($this->record_num - $start_index < $realPageSize){
                $realPageSize = $this->record_num - $start_index;
            }

            $limit =  $start_index. "," .$realPageSize;   
        }
        if($orderBy== null || $orderBy==""){
            $orderBy = $this->orderBy;
        }

        if ($ft != null) {
            $beanList = $this->bean->fetchBeanList($ft, $orderBy, $limit,$loadChild);
            //$this->record_num = $this->bean->getRecordCount($ft);
        } else {
            $beanList= $this->bean->fetchBeanList($this->filter, $orderBy, $limit,$loadChild);
            //$this->record_num = $this->bean->getRecordCount($this->filter);
        }
        

        $pageCtrl["page_no"] = $this->cur_page+0;
        $pageCtrl["page_size"] = $this->page_size+0;
        $pageCtrl["real_size"] = count($beanList)+0;
        $pageCtrl["record_count"] = $this->record_num+0;
        $pageCtrl["page_count"] = $this->page_count;
        $page["record_count"] = $this->record_num+0;
        $page["page_ctrl"] =$pageCtrl;
        $page["data_rows"] =$beanList;
      
        //print_r($rows);
        //echo json_encode($page);
        return $page;
    }

    public function jump_to($page_no) {
        $strHtml = "go_page(" . $page_no . ")";
        return $strHtml;
    }

    public function drawHidden() {
        $keys = array_keys($_REQUEST);
        for ($i = 0; $i < count($keys); $i++) {
            if (!empty($_REQUEST[$keys[$i]]) && $keys[$i] != "page_no") {
                echo "<input type=\"hidden\" name=\"" . $keys[$i] . "\"  value=\"" . $_REQUEST[$keys[$i]] . "\" >\r\n";
            }
        }
    }

    public function drawPageInfo($lan="cn") {
        $strHtml = "";
        try {
            $cur_page = 0;
            $next_page = 0;
            $prv_page = 0;
            $thiscount = $this->page_count;
            if (!empty($_REQUEST["cur_page"])) {
                $cur_page = $_REQUEST["cur_page"];
            }
            $display_start_no = 0;
            if ($this->record_num > 0) {
                $display_start_no = $cur_page * $this->page_size + 1;
            }
            $display_end_no = ($cur_page + 1) * $this->page_size;
            if ($display_end_no > $this->record_num) {
                $display_end_no = $this->record_num;
            }
			if($lan=="cn"){
           		$strHtml.= "第" . $display_start_no . "-" . $display_end_no . "条,共" . $this->record_num . "条," . ($this->cur_page + 1) . "页/" . $this->page_count . "页";
			}else{
				$strHtml.= "&nbsp;&nbsp;<b>".$display_start_no . "</b>-<b>" . $display_end_no . "</b> of <b>" . $this->record_num."</b>&nbsp;&nbsp;" ;	
			}
            if ($cur_page > 0) {
                $prv_page = $cur_page - 1;
                
				if($lan=="cn"){
					$strHtml = "<a  onclick=\"go_page(" . $prv_page . "); \" style='text-decoration:underline;color:#127bbd;font-weight:bold;cursor:pointer'>< 前一页 </a>\r\n" . $strHtml;
				}else{
					$strHtml = "<a  onclick=\"go_page(" . $prv_page . "); \" style='text-decoration:underline;color:#127bbd;font-weight:bold;cursor:pointer'>< Previous Page </a>\r\n" . $strHtml;
				}
            }else{
				if($lan=="cn"){
					$strHtml = "<span  style='text-decoration:none;color:#cccccc;'>< 前一页 </span>\r\n" . $strHtml;
				}else{
					$strHtml = "<span  style='text-decoration:none;color:#cccccc;'>< Previous Page </span>\r\n" . $strHtml;
				}	
			}
            if ($cur_page < $thiscount - 1) {
                $next_page = $cur_page + 1;
				if($lan=="cn"){
               		$strHtml = $strHtml . " <a  onclick=\"go_page(" . $next_page . "); \" style='text-decoration:underline;color:#127bbd;cursor:pointer;font-weight:bold'>后一页></a>\r\n";
				}else{
					$strHtml = $strHtml . " <a  onclick=\"go_page(" . $next_page . "); \" style='text-decoration:underline;color:#127bbd;cursor:pointer;font-weight:bold'>Next Page></a>\r\n";	
				}
            }else{
				if($lan=="cn"){
               		$strHtml = $strHtml . " <span  style='text-decoration:none;color:#cccccc;'>后一页></span>\r\n";
				}else{
					$strHtml = $strHtml . " <span  style='text-decoration:none;color:#cccccc;'>Next Page></span>\r\n";	
				}	
			}
			
			
			$StrReturn = "<select style='font-family:Verdana, Geneva, sans-serif; font-size:12px; color:#666666' name='txt_page_no' id='txt_page_no'>";
			$p1=($cur_page-10)>=0?($cur_page-10):1;
			
			$p2=($cur_page+10)>=$this->page_count?$this->page_count:($cur_page+10);
			
			for($m=$p1;$m<=$p2;$m++){
				$xxx=(($cur_page+1)==$m)?"selected":"";
				
				if($lan=="cn"){
					$StrReturn .= "<option value='".($m-1)."' ".$xxx.">第".$m."页</option>";
				}else{
					$StrReturn .= "<option value='".($m-1)."' ".$xxx.">P.".$m."</option>";
				}
			}
			
			if($this->page_count>$p2){
				$x=	(int)($this->page_count/10);
				$y=	(int)($p2/10);
				if($x>$y){
					for($n=$y;$n<=$x;$n++){
						if($lan=="cn"){
							$StrReturn .= "<option value='".($n*10+4)."'>第".($n*10)."-".($n*10+9)."页</option>";
						}else{
							$StrReturn .= "<option value='".($n*10+4)."'>P.".($n*10)."-".($n*10+9)."</option>";
						}
				
					}
				}
				
				if($lan=="cn"){
					$StrReturn .= "<option value='".($this->page_count-1)."'>最后一页</option>";
				}else{
					$StrReturn .= "<option value='".($this->page_count-1)."'>Last Page</option>";
				}
						
			}
			$StrReturn .= "</select>";
			
			$strHtml.=$StrReturn;
            $strHtml.= "<input type=\"hidden\" id=\"cur_page\"  name=\"cur_page\" value=\"" . $cur_page . "\" >";
            $strHtml.= "<input type=\"button\" id=\"btn_go\"  value=\" Go \" onclick=\"go_page(document.getElementById('txt_page_no').value)\"  >";
            $strHtml.= $this->createScript();
            if ($this->cache_filter) {
                $this->drawHidden();
            }
        }
        catch(Exception $ex) {
            echo $ex->getMessage();
        }
        return $strHtml;
    }

    public function createScript($createHidden = false) {
        $strHtml = "";
        if ($createHidden) {
            $cur_page = 0;
            if (!empty($_REQUEST["cur_page"])) {
                $cur_page = $_REQUEST["cur_page"];
            }

            //$strHtml.= "<input type=\"hidden\" id=\"cur_page\"  name=\"cur_page\" value=\"" . $cur_page . "\" >\r\n";
        }
        $strHtml.= "\r\n<script language=\"javascript\">\r\n";
        $strHtml.= "function go_page(page_no){\r\n";
        $strHtml.= " var txt_page= document.getElementById(\"cur_page\");\r\n";
        $strHtml.= " if(txt_page!=null){\r\n";
        $strHtml.= "	  txt_page.value=page_no;\r\n";
		//$strHtml.= "	  alert(txt_page.value);\r\n";
        $strHtml.= "	  document.forms[" . $this->submit_form_index . "].submit();\r\n";
        $strHtml.= " }\r\n}\r\n";
        $strHtml.= "</script>\r\n";
        return $strHtml;
    }
}
?>

